import axios from "axios";
import { getToken } from "@/utils/auth";
import { Message } from "@arco-design/web-vue";

axios.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers["satoken"] = `${token}`;
    }
    config.withCredentials = true;
    return config;
  },
  (error) => Promise.reject(error)
);

axios.interceptors.response.use(
  (response: any) => {
    const res = response.data;
    switch (res.code) {
      case 0:
        return response;
      case 200:
        return response;
      case 40100:
        Message.error({
          content: res.message || "未授权，请重新登录",
          showIcon: true,
        });
        window.location.href = "http://localhost:8080/login";
        break;
      default:
        Message.error({
          content: res.message || "请求失败，请稍后再试",
          showIcon: true,
        });
        return Promise.reject(new Error(res.message || "请求失败"));
    }
  },
  (error) => {
    if (error.response) {
      // 请求已发出但服务器响应的状态码不在 2xx 范围内
      console.error("Response Error:", error.response.data);
      console.error("Response Status:", error.response.status);
      console.error("Response Headers:", error.response.headers);
      Message.error({
        content: error.response.data.message || "请求失败，请稍后再试",
        showIcon: true,
      });
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error("Request Error:", error.request);
      Message.error({
        content: "请求超时或服务器未响应，请稍后再试",
        showIcon: true,
      });
    } else {
      // 一些设置请求时发生错误
      console.error("Error:", error.message);
      Message.error({
        content: "请求配置错误，请稍后再试",
        showIcon: true,
      });
    }
    return Promise.reject(error);
  }
);
